package com.cheyunkeji.er.activity.auction;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.CarSourceCitySelectActivity;
import com.cheyunkeji.er.activity.evaluate.EditRemarksActivity;
import com.cheyunkeji.er.activity.evaluate.PhotoPreViewActivity;
import com.cheyunkeji.er.app.UserInfoManager;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.auction.CarDealerInfo;
import com.cheyunkeji.er.bean.evaluate.CarInfo;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.service.OssService;
import com.cheyunkeji.er.utils.ImageLoadUtil;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.cheyunkeji.er.view.evaluate.ImageSelectDialog;
import com.cheyunkeji.er.view.evaluate.TakePhotoDisplayView;
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.utils.ImageCaptureManager;
import okhttp3.Call;
import okhttp3.Request;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

public class EditPersonalInfoActivity extends BaseActivity implements   EasyPermissions.PermissionCallbacks, TakePhotoDisplayView.OnTakePhotoListener, OssService.onImageProcessedResultListener, ImageSelectDialog.ImageSelectListener {
    private static final int REQUEST_NECESSARY_PMS_CODE = 0X110;
    private static final int REQUEST_CODE_EDIT_CSMC = 0x1001;
    private static final int REQUEST_CODE_EDIT_LXR = 0x1002;
    private static final int REQUEST_CODE_EDIT_TELE_NUMBER = 0x1003;
    private static final int REQUEST_CODE_EDIT_CS_INTRO = 0x1004;
    private static final int PREVIEW_IMG_REQUEST = 0x133;
    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_csmc)
    TextView tvCsmc;
    @BindView(R.id.tv_lxr)
    TextView tvLxr;
    @BindView(R.id.tv_tele_number)
    TextView tvTeleNumber;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_cs_desc)
    TextView tvCsDesc;
    @BindView(R.id.btn_submit_modify)
    Button btnSubmitModify;
    @BindView(R.id.activity_setting)
    LinearLayout activitySetting;
    @BindView(R.id.tpdv_license)
    TakePhotoDisplayView tpdvLicense;

    private String TAG = EditPersonalInfoActivity.class.getSimpleName();

    private CarDealerInfo carDealerInfo;
    private CarInfo.CarSourceCity sourceCity;
    private CarInfo.CarSourceCity sourceProvince;
    private ImageSelectDialog imgSelectDialog;
    private ImageCaptureManager captureManager;

    String[] perms = {Manifest.permission.CAMERA, WRITE_EXTERNAL_STORAGE};//权限列表

    @Override
    protected void init() {
        setContentView(R.layout.er_activity_edit_personal_info);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {

        vTopbar.setTitle("资料编辑");
        vTopbar.setLeftBack();
        tvAddress.setOnClickListener(this);
        tvCsmc.setOnClickListener(this);
        tvLxr.setOnClickListener(this);
        tvTeleNumber.setOnClickListener(this);
        tvCsDesc.setOnClickListener(this);
        tpdvLicense.setListener(this);
        btnSubmitModify.setOnClickListener(this);

        tvAccount.setText(UserInfoManager.getInstance(this).getMobile());
        tvName.setText(UserInfoManager.getInstance(this).getRealName());
        captureManager = new ImageCaptureManager(this);

    }

    @Override
    protected void initData() {

        loadCarDealerInfo();
    }

    public void showImgSelectDialog(String titleStr) {

        if (null == imgSelectDialog) {
            imgSelectDialog = new ImageSelectDialog(this, this, titleStr);
        } else {
            imgSelectDialog.setTitleStr(titleStr);
        }
        imgSelectDialog.show();

    }

    private void loadCarDealerInfo() {

        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());

        ApiClient.postForm(HttpConstants.GET_CAR_DEALER_INFO, params,

                new StringCallback() {

                    @Override
                    public void onError(Call call, Exception e, int id) {

                        if (e instanceof UnknownHostException || e instanceof SocketException) {
                            SToast.show(R.string.tip_network_error, Gravity.CENTER);
                            return;
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        try {
                            JSONObject obj = new JSONObject(response);

                            if (obj.optString("code").equals("1")) {

                                carDealerInfo = new Gson().fromJson(obj.optString("data"), CarDealerInfo.class);
                                if (null != carDealerInfo) {
                                    displayInfo(carDealerInfo);
                                } else {
                                    carDealerInfo = new CarDealerInfo();
                                }
                            } else {
                                SToast.show(obj.optString("msg"));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onBefore(Request request, int id) {
                        showDialog();
                    }

                    @Override
                    public void onAfter(int id) {
                        dismissDialog();
                    }

                }
        );

    }


    private void displayInfo(CarDealerInfo data) {

        if (!TextUtils.isEmpty(data.getTitle())) {
            tvCsmc.setText(data.getTitle());
        }

        if (!TextUtils.isEmpty(data.getRealname())) {
            tvLxr.setText(data.getRealname());
        }

        if (!TextUtils.isEmpty(data.getMobile())) {
            tvTeleNumber.setText(data.getMobile());
        }
        if (!TextUtils.isEmpty(data.getIntro())) {
            tvCsDesc.setText(data.getIntro());
        }
        if (!TextUtils.isEmpty(data.getLicimg()) && data.getLicimg().startsWith("http")) {
            ImageLoadUtil.loadImg(this, data.getLicimg(), tpdvLicense.getImageView());
            tpdvLicense.setPhotoBtnState(true);
            tpdvLicense.setImgPath(data.getLicimg());
        }

        if (!TextUtils.isEmpty(data.getRegion())) {
            String[] address = data.getRegion().split(",");
            if (address != null && address.length != 0) {
                tvAddress.setText(address[0] + address[1]);
            }
        }

    }

    /**
     * 进入图片选择页面
     */
    private void pickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .start(this);
    }


    @Override
    public void onClick(View v) {

        Intent intent;
        Bundle bundle;

        switch (v.getId()) {
            case R.id.btn_submit_modify:

                if (verifyInput())
                    submitModify();
                break;
            case R.id.tv_address:

                intent = new Intent(this, CarSourceCitySelectActivity.class);
                startActivityForResult(intent, Constants.REQUEST_CODE_SELECT_CITY);
                break;
            case R.id.tv_csmc:
                intent = new Intent(this, EditRemarksActivity.class);
                bundle = new Bundle();

                if (!TextUtils.isEmpty(tvCsmc.getText().toString()))
                    bundle.putString(Constants.EDITING_CONTENT, tvCsmc.getText().toString());
                bundle.putString(Constants.EDITING_TITLE, "车商名称");
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE_EDIT_CSMC);

                break;
            case R.id.tv_lxr:
                intent = new Intent(this, EditRemarksActivity.class);
                bundle = new Bundle();

                if (!TextUtils.isEmpty(tvLxr.getText().toString()))
                    bundle.putString(Constants.EDITING_CONTENT, tvLxr.getText().toString());

                bundle.putString(Constants.EDITING_TITLE, "联系人");
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE_EDIT_LXR);
                break;
            case R.id.tv_tele_number:
                intent = new Intent(this, EditRemarksActivity.class);
                bundle = new Bundle();

                if (!TextUtils.isEmpty(tvTeleNumber.getText().toString()))
                    bundle.putString(Constants.EDITING_CONTENT, tvTeleNumber.getText().toString());

                bundle.putString(Constants.EDITING_TITLE, "联系电话");
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE_EDIT_TELE_NUMBER);

                break;

            case R.id.tv_cs_desc:
                intent = new Intent(this, EditRemarksActivity.class);
                bundle = new Bundle();

                if (!TextUtils.isEmpty(tvCsDesc.getText().toString()))
                    bundle.putString(Constants.EDITING_CONTENT, tvCsDesc.getText().toString());

                bundle.putString(Constants.EDITING_TITLE, "车商简介");
                bundle.putBoolean(EditRemarksActivity.MULTIPLE_EDIT_LINES,true);
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE_EDIT_CS_INTRO);
                break;

            default:
                break;
        }

    }

    private boolean verifyInput() {

        if (TextUtils.isEmpty(tvCsmc.getText().toString())) {
            SToast.show("车商名称不能为空");
            return false;
        }

        if (TextUtils.isEmpty(tvLxr.getText().toString())) {
            SToast.show("联系人不能为空");
            return false;
        }

        if (TextUtils.isEmpty(tvTeleNumber.getText().toString())) {
            SToast.show("联系电话不能为空");
            return false;
        }

        if (TextUtils.isEmpty(tvAddress.getText().toString())) {
            SToast.show("省份城市不能为空");
            return false;
        }

        if (TextUtils.isEmpty(tvCsDesc.getText().toString())) {
            SToast.show("车商简介不能为空");
            return false;
        }

        if (TextUtils.isEmpty(tpdvLicense.getImagePath())) {
            SToast.show("营业执照不能为空");
            return false;
        }
        return true;

    }

    private void submitModify() {

        Log.e(TAG, "submitModify: License Img Path : " + carDealerInfo.getLicimg());

        if (!TextUtils.isEmpty(carDealerInfo.getLicimg()) && !carDealerInfo.getLicimg().startsWith("http")) {

            MyApplication.getInstance().getOssService(this).asyncPutImage(OssService.getOssObjectInfo(true),
                    carDealerInfo.getLicimg(), "");

            showDialog();

        } else
            saveData();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case Constants.REQUEST_CODE_SELECT_CITY:

                if (data != null && null != data.getSerializableExtra("SOURCE_CITY")) {
                    sourceCity = (CarInfo.CarSourceCity) data.getSerializableExtra("SOURCE_CITY");
                    carDealerInfo.setCity(sourceCity.getId());
                }

                if (null != data && null != data.getSerializableExtra("SOURCE_PROVINCE")) {
                    sourceProvince = (CarInfo.CarSourceCity) data.getSerializableExtra("SOURCE_PROVINCE");
                    carDealerInfo.setProvince(sourceProvince.getId());
                }

                if (null != data && null != sourceProvince && null != sourceCity) {
                    tvAddress.setText(sourceProvince.getName() + sourceCity.getName());
                    carDealerInfo.setRegion(new StringBuffer(sourceProvince.getName()).append(",").append(sourceCity.getName()).toString());
                }

                break;

            case ImageCaptureManager.REQUEST_TAKE_PHOTO:

                if (resultCode == RESULT_OK) {
                    captureManager.galleryAddPic();
                    String path = captureManager.getCurrentPhotoPath();
                    ImageLoadUtil.loadImg(this, path, tpdvLicense.getImageView());
                    tpdvLicense.setImgPath(path);
                    tpdvLicense.setPhotoBtnState(true);
                    carDealerInfo.setLicimg(path);
                }

                break;

            case PhotoPicker.REQUEST_CODE:
                if (data != null) {
                    String localImgPath = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0);
                    if (!TextUtils.isEmpty(localImgPath)) {
                        ImageLoadUtil.loadImg(this, localImgPath, tpdvLicense.getImageView());
                        tpdvLicense.setImgPath(localImgPath);
                        tpdvLicense.setPhotoBtnState(true);
                        carDealerInfo.setLicimg(localImgPath);
                    }

                }
                break;

            case REQUEST_CODE_EDIT_CSMC:

                if (resultCode == RESULT_OK) {
                    tvCsmc.setText(data.getStringExtra(Constants.EDITED_CONTENT));
                    carDealerInfo.setTitle(data.getStringExtra(Constants.EDITED_CONTENT));
                }

                break;

            case REQUEST_CODE_EDIT_LXR:
                if (resultCode == RESULT_OK) {
                    tvLxr.setText(data.getStringExtra(Constants.EDITED_CONTENT));
                    carDealerInfo.setRealname(data.getStringExtra(Constants.EDITED_CONTENT));
                }
                break;

            case REQUEST_CODE_EDIT_TELE_NUMBER:
                if (resultCode == RESULT_OK) {
                    tvTeleNumber.setText(data.getStringExtra(Constants.EDITED_CONTENT));
                    carDealerInfo.setMobile(data.getStringExtra(Constants.EDITED_CONTENT));
                }
                break;

            case REQUEST_CODE_EDIT_CS_INTRO:
                if (resultCode == RESULT_OK) {
                    tvCsDesc.setText(data.getStringExtra(Constants.EDITED_CONTENT));
                    carDealerInfo.setIntro(data.getStringExtra(Constants.EDITED_CONTENT));
                }
                break;

            case PREVIEW_IMG_REQUEST:

                if (data == null) {
                    return;
                }

                boolean deleteImg = data.getBooleanExtra("DELETE_IMG", false);

                if (deleteImg && carDealerInfo != null) {

                    tpdvLicense.setImgPath("");
                    tpdvLicense.setPhotoBtnState(false);
                    tpdvLicense.getImageView().setImageDrawable(null);
                    carDealerInfo.setLicimg("");
                }
                break;

            default:
                break;
        }

    }

    @Override
    public void takePhoto(int itemIndex) {


        if (null != carDealerInfo && !TextUtils.isEmpty(carDealerInfo.getLicimg())) {

            //          有照片，预览照片
            Intent intent = new Intent(this, PhotoPreViewActivity.class);
            intent.putExtra("IMG_PATH", carDealerInfo.getLicimg());
            this.startActivityForResult(intent, PREVIEW_IMG_REQUEST);
        } else {
            showImgSelectDialog("");
        }

    }

    @Override
    public void onUploadOk(String imgUrl, Object tag) {

        if (!TextUtils.isEmpty(imgUrl)) {
            carDealerInfo.setLicimg(imgUrl);
            tpdvLicense.setImgPath(imgUrl);
            saveData();
        }
    }

    private void saveData() {

        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());

        params.put("title", carDealerInfo.getTitle());
        params.put("realname", carDealerInfo.getRealname());
        params.put("mobile", carDealerInfo.getMobile());
        params.put("province", String.valueOf(carDealerInfo.getProvince()));
        params.put("city", String.valueOf(carDealerInfo.getCity()));
        params.put("licimg", carDealerInfo.getLicimg());
        params.put("intro", carDealerInfo.getIntro());
        params.put("region", carDealerInfo.getRegion());

        ApiClient.postForm(HttpConstants.MODIFY_CAR_DEALER_INFO, params, new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                    return;
                }
            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject obj = new JSONObject(response);

                    if (obj.optInt("code", 0) == 1) {
                        SToast.show("车商信息修改成功！");

                        if (getIntent().getBooleanExtra("IS_FROM_BINDER", false)) {
                            MyApplication.getInstance().removeActivity(EditPersonalInfoActivity.class);
                        }

                    } else {
                        SToast.show(obj.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }

            @Override
            public void onAfter(int id) {
                dismissDialog();
            }

        });

    }

    @Override
    public void onUploadFailed() {
        Log.e(TAG, "onUploadFailed: OSS 图片上传失败");
    }

    private void openSystemCamera() {
        Intent intent = null;
        try {
            intent = captureManager.dispatchTakePictureIntent();
            startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTakePhotoWithSystemCamera() {
        openSystemCamera();
    }

    @Override
    public void onSelectImgOnGallery() {
        requestNecessaryPms();

    }



    @AfterPermissionGranted(REQUEST_NECESSARY_PMS_CODE)
    private void requestNecessaryPms() {


        if (EasyPermissions.hasPermissions(this, perms)) {
            pickPhoto();
        } else {
            // Do not have permissions, request them now
//            EasyPermissions.requestPermissions(this, getString(R.string.request_necessary_pms),
//                    REQUEST_NECESSARY_PMS_CODE, perms);
            EasyPermissions.requestPermissions(this, "需要获取拍照，存储权限",
                    REQUEST_NECESSARY_PMS_CODE, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {

//            new AppSettingsDialog.Builder(this).build().show();
            new AppSettingsDialog.Builder(this)
                    .setRationale("没有该权限，此应用程序可能无法正常工作。打开应用设置界面以修改应用权限")
                    .setTitle("必需权限")
                    .build()
                    .show();
        } else if (!EasyPermissions.hasPermissions(this, this.perms)) {
            //这里响应的是除了AppSettingsDialog这个弹出框，剩下的两个弹出框被拒绝或者取消的效果
//            quitEvaluateWorkflow();
        }

    }
}
